<template>
  <el-cascader ref="contentRef" v-bind="$attrs" :filterable="filterable" :clearable="clearable" :options="options" :props="cascaderProps" :show-all-levels="showAllLevels"
    :collapse-tags-tooltip="collapseTagsTooltip" :filter-method="filterMethod" @change="change" />
</template>
<script setup>
import useCommonStore from "@/store/modules/common";
import baseApi from './api'
import * as api from '@/api/public'

const props = defineProps({
  type: { type: String, default: '0' },
  multiple: Boolean,
  areaLevel: { type: Number, default: () => 10 },
  filterable: { type: Boolean, default: true },
  clearable: { type: Boolean, default: true },
  showAllLevels: Boolean,
  collapseTagsTooltip: { type: Boolean, default: true },
});

const attrs = useAttrs()
const config = {
  0: {
    key: 'personnel', // 人员
    value: 'user_id'
  },
  1: {
    key: 'department', // 部门
  },
  2: {
    key: 'classify', // 分类
    children: 'son'
  },
  3: {
    key: 'area', // 区域
    lazy: true,
    lazyLoad(node, resolve) {
      const { root, value } = node
      api.area({ parent_id: root ? 0 : value }).then(res => {
        const nodes = res.data.map(item => ({
          value: item.area_id,
          label: item.area_name,
          leaf: item.level > ((props.areaLevel || 3) - 1)
        }))
        resolve(nodes)
      })
    },
  },
  4: {
    key: 'platform_category', // 平台类目
    lazy: true,
    lazyLoad(node, resolve) {
      const { root, value } = node
      const { site_id } = attrs
      if (!site_id) {
        resolve([])
        return
      }
      baseApi.getCategory({ category_id: root ? '' : value, site_id }).then(res => {
        const nodes = res.data.map(item => ({
          value: item.category_id,
          label: item.category_name,
          leaf: item.leaf
        }))
        resolve(nodes)
      })
    },
  },
}

const commonStore = useCommonStore();
const item = config[props.type]
const { key, children = 'sub' } = item
function getFirstTwoLevels(arr, le) {
  function getFirstTwoLevelsRecursive(currentArr, level) {
    currentArr.forEach(item => {
      if (level > le) {
        item[children] = []
        return
      } else if (item[children]?.length) {
        item[children] = item[children].map(d => ({ ...d, disabled: d.status === 0 }))
        getFirstTwoLevelsRecursive(item[children], level + 1);
      }
    })
  }

  getFirstTwoLevelsRecursive(arr, 1);
  return arr;
}
const keyName = props.areaLevel ? key + props.areaLevel : key
if (!commonStore.options[keyName] && !item.lazy) {
  try {
    api[key]().then(data => {
      commonStore.setOptions(keyName, props.areaLevel ? getFirstTwoLevels(data, props.areaLevel) : data)
    })
  } catch (error) {
    console.log('error', error)
  }
}
const options = computed(() => item.lazy ? [] : commonStore.options[keyName])
const cascaderProps = computed(() => {
  const { lazy, lazyLoad, label = 'name', value = 'id', children = 'sub' } = item
  if (item.lazy) return { lazy, lazyLoad }
  return {
    emitPath: false,
    multiple: props.multiple,
    label,
    value,
    children,
  }
})

const filterMethod = (node, val) => {
  if (!!~node.text.indexOf(val) || !!~node.text.toUpperCase().indexOf(val.toUpperCase())) {
    return true
  }
}

const emit = defineEmits(['change'])

const contentRef = ref()
const change = (value) => {
  const getCheckedNodes = contentRef?.value.getCheckedNodes()
  const labels = props.multiple ? getCheckedNodes.map(d => d.label) : getCheckedNodes[0].pathLabels
  emit('change', { value, labels })
}

</script>